<template>
  <a-drawer
      title="线索跟进"
      :visible="visible"
      :destroyOnClose="true"
      :width="460"
      :body-style="{
      height: 'calc(100% - 100px)',
      boxSizing: 'border-box',
      padding: '16px 0',
    }"
      @close="onClose"
  >

    <div class="drawer-content">
      <div style="padding: 0 16px">
        <a-alert type="info" v-if="!processApprove" style="margin-bottom: 10px;">
          <template #message>
            线索转客户暂未开启审批，点击”
            <span v-if="Approveis_admin" class="link" @click.stop="goSetting">配置</span>
            <span v-else class="link" style="cursor: not-allowed;">配置</span>
            “可快速设置。
          </template>
        </a-alert>
      </div>
      <a-radio-group
          v-model:value="activeKey"
          class="radio-box"
          button-style="solid"
      >
        <a-radio-button value="1" style="flex: 1">跟进线索</a-radio-button>
        <a-radio-button value="2" style="flex: 1">线索信息</a-radio-button>
      </a-radio-group>

      <div class="content-box" v-show="activeKey == '1'">
        <div class="mt-10">
          <a-form ref="formRef" layout="vertical" :model="followForm">
            <a-form-item label="变更线索状态" name="status"
                         :rules=" [{ required: true,message: '请选择跟进状态',}]">
              <a-select
                  v-model:value="followForm.status"
                  placeholder="请选择"
                  :options="optionsStatus"
              ></a-select>
            </a-form-item>

            <a-form-item label="跟进内容">
              <a-textarea
                  placeholder="输入跟进内容"
                  v-model:value="followForm.status_content"
              ></a-textarea>
            </a-form-item>

            <a-form-item label="下次跟进时间" v-if="followForm.status!=33">
              <a-date-picker
                  :show-time="{ format: 'HH:mm' }"
                  placeholder="选择时间"
                  format="YYYY-MM-DD HH:mm"
                  style="width: 100%"
                  v-model:value="followForm.next_time"
              />
            </a-form-item>

            <a-form-item label="是否公开到渠道" v-if="formsPut.channel_id">
              <a-switch
                  :checked="followForm.public_channel == 1"
                  @change="
                  followForm.public_channel =
                    followForm.public_channel == 0 ? 1 : 0
                "
              />
            </a-form-item>
            <a-form-item label="跟进图片">
              <a-upload
                  :action="imgAction"
                  v-model:file-list="fileList"
                  :multiple="false"
                  accept="image/*"
                  name="image"
                  list-type="picture-card"
                  :headers="{ 'org-token': $store.getters.token }"
                  :data="{ dir: 'org_village' }"
                  @change="handleUploadChange"
              >
                <div v-if="fileList.length < 6">
                  <PlusOutlined/>
                  <div style="padding-top: 4px">上传</div>
                </div>
              </a-upload>
            </a-form-item>


            <a-col :span="24">
              <div style="margin-bottom: 16px">跟进历史</div>
              <a-timeline v-if="remarksList.length">
                <a-timeline-item v-for="(item, index) in remarksList">
                  <p>
                    {{ item.created_at }}
                  </p>
                  <p v-if="item?.operate_content?.status_txt">
                    状态：{{ item.operate_content.status_txt || "--" }}
                  </p>
                  <p v-if="item?.operate_content?.remark">
                    内容：{{ item.operate_content.remark || "--" }}
                  </p>
                  <div class="mb-10 flex" v-if="item.operate_content?.followup_img?.length>0">
                    <span>跟进图片：</span>
                    <a-space>
                      <a-image v-for="img in item.operate_content?.followup_img" :src="img.url"
                               :width="40"/>
                    </a-space>
                  </div>
                  <p
                      v-if="
                      item?.operate_content?.user_name ||
                      item?.operate_content?.user_phone
                    "
                  >
                    跟进人： {{ item?.operate_content?.user_name }}
                    {{ item?.operate_content?.user_phone }}
                  </p>
                </a-timeline-item>
              </a-timeline>

              <a-empty v-else/>
            </a-col>
          </a-form>
        </div>
      </div>

      <!-- 线索信息 -->
      <div class="content-box" v-show="activeKey == '2'">
        <div class="mt-10">
          <a-form :model="formsPut" layout="vertical">
            <template v-for="field in templateFields" :key="field.alias">
              <a-form-item
                  label="客户名称"
                  name="contact_name"
                  v-bind="validateInfos.contact_name"
                  v-if="field.alias=='contact_name'"
              >
                <a-input
                    v-model:value="formsPut.contact_name"
                    placeholder="请输入客户名称"
                />
              </a-form-item>

              <a-form-item
                  label="客户手机号"
                  name="contact_phone"
                  v-bind="validateInfos.contact_phone"
                  v-if="field.alias=='contact_phone'"
              >
                <a-input
                    v-model:value="formsPut.contact_phone"
                    placeholder="请输入客户手机号"
                />
              </a-form-item>

              <a-form-item label="公司" v-if="field.alias=='company'">
                <a-input
                    v-model:value="formsPut.company"
                    placeholder="请输入所属公司"
                />
              </a-form-item>

              <a-form-item label="选择项目" v-bind="validateInfos.build_ids"
                           v-if="field.alias=='village_id'">
                <a-cascader
                    v-model:value="formsPut.build_ids"
                    :options="optionsBuild"
                    placeholder="请选择"
                />
              </a-form-item>
              <a-form-item label="需求面积段" v-if="field.alias=='expect_area'">
                <a-input-group size="default">
                  <a-row :gutter="8">
                    <a-col :span="8">
                      <a-input-number
                          addon-after="m²"
                          :min="0"
                          v-model:value="formsPut.expect_area_min"
                          placeholder="最小值"
                      />
                    </a-col
                    >
                    -
                    <a-col :span="8">
                      <a-input-number
                          addon-after="m²"
                          :min="0"
                          v-model:value="formsPut.expect_area_max"
                          placeholder="最大值"
                      />
                    </a-col>
                  </a-row>
                </a-input-group>
              </a-form-item>

              <a-form-item label="备注" v-if="field.alias=='remark'">
                <a-textarea
                    v-model:value="formsPut.remark"
                    placeholder="请输入备注"
                    :rows="4"
                />
              </a-form-item>

            </template>


            <div class="title">附加字段</div>
            <a-col :span="24" v-if="detail.diy_field&&detail.diy_field.length>0">
              <template v-for="field in detail.diy_field">
                <div class="m-t-20"
                     v-if="field.type=='input'||field.type=='textarea'||field.type=='singleSelect'">
                  <span>{{ field.name }}：</span>
                  <span>{{ field.content }}</span>
                </div>
                <div class="m-t-20"
                     v-else-if="field.type=='mutiSelect'">
                  <span>{{ field.name }}：</span>
                  <template v-for="(contentItem,index) in field.content">
                    <span v-if="index!=0">,</span>
                    <span>{{ contentItem }}</span>
                  </template>
                </div>
                <div class="m-t-20"
                     v-else-if="field.type=='image'">
                  <span>{{ field.name }}：</span>
                  <a-space>
                    <a-image v-for="src in field.content" :src="src.url" :width="50"/>
                  </a-space>

                </div>
                <div class="m-t-20 flex flex-start"
                     v-else-if="field.type=='file'">
                  <div>{{ field.name }}：</div>
                  <div class="flex-1">
                    <template v-for="(src,index) in field.content">
                      <div class="text-blue" style="cursor: pointer"
                           @click.stop="downloadFile(src.url)">{{ index + 1 }}.{{ src.name }}
                      </div>
                    </template>
                  </div>
                </div>
              </template>
            </a-col>


          </a-form>


        </div>
      </div>

      <div
          :style="{
          position: 'absolute',
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e8e8e8',
          padding: '10px 16px',
          textAlign: 'right',
          left: 0,
          background: '#fff',
          borderRadius: '0 0 4px 4px',
          display: 'flex',
          justifyContent: 'space-between',
        }"
      >
        <a-button type="primary" danger @click="backToPool">退回公海</a-button>
        <div>
          <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
          <a-button type="primary" @click="submitClick">
            {{ processApprove ? '确定&发起审批' : '确定' }}
          </a-button>
        </div>
      </div>
    </div>
  </a-drawer>
</template>

<script>
import {watch, ref, reactive, toRefs, createVNode} from "vue";
import request from "../../../../common/utils/request";
import {message} from "ant-design-vue";
import {Form, Modal} from "ant-design-vue";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons-vue";
import store from '@/store'
import utils from '@/common/utils/utils'

const useForm = Form.useForm;
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
  },
  components: {PlusOutlined, ExclamationCircleOutlined},
  setup(props, context) {
    const state = reactive({
      detail: {},
      templateFields: [],
      processApprove: false,    //判断是否开启
      Approveis_admin: false,   //判断是否有权限
      Approve_id: 0,
    });

    const formRef = ref();
    const followForm = reactive({
      status: undefined,
      status_content: "", //跟进内容
      values: "",
      operation_uid: undefined,
      next_time: "",
      public_channel: 1,
    });

    const formsPut = reactive({
      contact_name: "",
      contact_phone: "",
      company: "",
      building: "",
      build_ids: undefined,
      village_id: undefined,
      build_id: undefined,
      expect_area_min: "",
      expect_area_max: "",
      area: "",
      channel_id: undefined,
      remark: "",
    });

    const rulesRef = reactive({

      contact_name: [
        {
          required: true,
          message: "请输入联系人姓名",
        },
      ],
      contact_phone: [
        {
          required: true,
          message: "请输入联系电话",
        },
      ],
      build_ids: [
        {
          required: true,
          message: "请选择意向项目",
        },
      ],
    });

    const {resetFields, validate, validateInfos} = useForm(
        formsPut,
        rulesRef
    );

    // 提交跟进表单
    const submitClick = () => {

      formRef.value.validateFields().then(() => {
        validate().then((res) => {
          let params = {};
          formsPut.status_content = followForm.status_content;
          formsPut.next_time = followForm.next_time
              ? followForm.next_time.format("YYYY-MM-DD HH:mm")
              : "";
          if (followForm.status) {
            formsPut.status = followForm.status;
            if (followForm.status == 33) {
              delete formsPut.next_time;
            }
          }
          formsPut.operation_uid = followForm.operation_uid || "";
          formsPut.operation_name = operation_name.value || "";

          if (formsPut.channel_id) {
            formsPut.public_channel = followForm.public_channel;
          }
          if (formsPut.build_ids.length > 0) {
            console.log(formsPut.build_ids);
            formsPut.village_id = formsPut.build_ids[0];
            formsPut.build_id =
                formsPut.build_ids.length > 1 ? formsPut.build_ids[1] : undefined;
          }

          if (fileList.value.length > 0) {
            formsPut.followup_img = fileList.value.map(item => {
              return {
                name: item.name,
                url: item.url
              }
            })
          }

          delete formsPut.channel_id;
          delete formsPut.build_ids;
          params = formsPut;
          params.processApprove = state.processApprove;

          request.put("/org", "/business/clue", params).then((res) => {
            console.log(res);
            message.success(res.msg || "更新成功");
            // HouseholdList();
            // pop.value = false;
            state.list = [];
            followForm.status_content = "";
            followForm.next_time = "";
            context.emit("back");
          });
        }).catch(e => {
          activeKey.value = '2'
        });
      }).catch(e => {
      })

    };
    // let ids = 0;
    // let name = "";
    // let phone = "";
    const handleReset = (clearFilters, confirm) => {
      clearFilters();
      page.value = 1;
      confirm();
    };

    const activeKey = ref("1");

    // 跟进
    const remarksList = ref([]);
    const getDetail = () => {
      const id = props.id;
      request
          .get("/org", "/business/clue/detail", {
            id,
          })
          .then((res) => {
            state.detail = res.detail;
            console.log(state.detail)
            // followForm.status = Number(detail.status); //不回显状态
            followForm.status = undefined;

            setModelRef(state.detail);
            followForm.operation_uid = state.detail.operation_uid;
          });
    };
    const getRemarkList = () => {
      request
          .get("/org", "/business/clue/clueFollowRecord", {id: props.id})
          .then((res) => {
            console.log(res.list);
            remarksList.value = res.list;
          });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        formsPut[key] = state[key];
      }

      formsPut.build_ids = [];
      if (formsPut.village_id) {
        formsPut.build_ids.push(formsPut.village_id);
      }
      if (formsPut.build_id) {
        formsPut.build_ids.push(formsPut.build_id);
      }
    };

    const operation_name = ref("");
    const handleOperation = (value, change) => {
      operation_name.value = change.label;
    };

    const onClose = () => {
      context.emit("onClose");
    };

    // 退回公海
    const backToPool = () => {
      Modal.confirm({
        title: () => "提示",
        content: () => "确定要将该线索退回公海吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        okText: () => "确定",
        onOk() {
          request
              .post("/org", "/business/clue/backPool", {id: props.id})
              .then((res) => {
                message.success("操作成功！");
                context.emit("back");
              });
        },
      });
    };

    //线索状态
    const optionsStatus = ref([]);
    const getStatusList = () => {
      request.get("/org", "/business/clueStatus/clueStatusList").then((res) => {
        console.log(res);
        const temList = res.list.map((item) => {
          return {
            label: item.name,
            value: item.status,
          };
        });
        optionsStatus.value = temList;
      });
    };

    // 意向楼宇
    const optionsBuild = ref([]);
    const getBuildList = () => {
      request
          .get("/org", "/build/villageAndBuildList/v2")
          .then((res) => {
            const vList = res.villageList.map((item) => {
              return {
                label: item.name,
                value: item.id,
                children: item.buildList.map((childItem) => {
                  return {
                    label: childItem.build_name,
                    value: childItem.id,
                  };
                }),
              };
            });
            optionsBuild.value = vList;
          });
    };

    const goSetting = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: state.Approve_id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };

    const getDefaultField = () => {
      const params = {
        is_root: 1,
      }
      request.get("/org", "/business/clueField/getClueDiyField", params).then(res => {
        state.templateFields = res.data
      })

    }

    const getSetting = () => {
      // 获取配置
      request.get("/org", "/approval/publish/process", {
        alias: 'clue_to_customer_apply'
      }).then((res) => {
        console.log(res)
        state.processApprove = res.info.process    //判断是否开启
        state.Approveis_admin = res.info.is_admin    //判断是否有权限
        state.Approve_id = res.info.id
      });
    };


    const init = () => {
      getSetting();
      getDetail();
      getRemarkList();
      getStatusList();
      getBuildList();
      getDefaultField();
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            fileList.value = [];
            resetFields()
          }
        }
    );

    const downloadFile = (src) => {
      window.open(src);
    };

    const fileList = ref([]);
    // 上传
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length > 0) {
        // console.log(resFileList, "取最后一条数据之前");
        resFileList = resFileList.slice(-1);
        // console.log(resFileList, "取最后一条数据");

        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;

              // fileList.value.push({
              //   name: file.name,
              //   url: file.fileUrl,
              // });
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });

        console.log(resFileList, "最终数据");

        console.log(fileList.value);
      }
    };

    return {
      followForm,
      ...toRefs(state),
      formsPut,
      activeKey,
      remarksList,
      backToPool,
      onClose,
      optionsStatus,
      submitClick,
      formRef,
      validateInfos,
      optionsBuild,
      downloadFile,
      fileList,
      handleUploadChange,
      imgAction: request.BASE_URL + "/public/system/uploadImage",
      goSetting,

    };
  },
};
</script>

<style lang="less" scoped>
.drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.radio-box {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  text-align: center;
  padding: 0 16px;
}

.content-box {
  flex: 1;
  padding: 0 16px;
  overflow: auto;
}

:deep(.ant-image) {
  width: 50px;
  height: 50px;
  border-radius: 5px;
  overflow: hidden;
}

.title {
  height: 30px;
  line-height: 30px;
  color: #333;
  font-weight: 500;
  font-size: 15px;
  position: relative;
  padding-left: 10px;
}

.title::before {
  content: "";
  position: absolute;
  left: 0px;
  top: 8px;
  width: 4px;
  height: 14px;
  background-color: #1c90ff;
  border-radius: 4px;
}

.m-t-20 {
  margin-top: 20px;
}

:deep(.ant-image-img) {
  width: 40px;
  height: 40px;
  border-radius: 5px;
  overflow: hidden;
}
</style>
